#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

void ChildRun()
{
  int cnt = 5;
  //int* p = NULL;

  while(cnt)
  {
    printf("I am child process, pid: %d, ppid: %d, cnt: %d\n", getpid(), getppid(), cnt);
    sleep(1);
    cnt--;
    //*p = 100;
  }
}

int main()
{
  printf("I am father, pid: %d, ppid: %d\n", getpid(), getppid());

  pid_t id = fork();
  if(id == 0)
  {
    ChildRun();
    printf("child quit ...\n");
    exit(1);  
  }
  //sleep(7);
  //pid_t rid = wait(NULL);
  // waitpid 的功能：等待一个进程结束，
  // 回收 pid 为 id 的进程，并将被回收进程的退出信息放到输出型参数 status中
  // WIFEXITED可以对 status 进行解读
  // status的低7位，是进程的退出信号，高8位是退出码
  int status = 0;
  pid_t rid = waitpid(id, &status, 0); 
  if(rid > 0)
  {
    if(WIFEXITED(status))
    {
      printf("child quit success! child exit code: %d\n", WEXITSTATUS(status));
    }
    else 
    {
      printf("child quit abnormal!\n");
    }
    printf("wait success, rid: %d\n", rid);
  }
  else
  {
    printf("wait failed!\n");
  }
  sleep(3);
//printf("father quit, status: %d, child quit code: %d, child quit signal: %d\n", status, (status>>8)&0xFF, status & 0x7F);
}

//int main()
//{
//  printf("hello 111");
//  sleep(2);
//
//  _exit(3);
//}


//enum
//{
//  Success = 0,
//  Div_zero,
//  Mod_zero,
//};
//
//int exit_code = Success;
//
//const char *CodeToErrString(int code)
//{
//  switch(code)
//  {
//    case Success:
//      return "Success";
//    case Div_zero:
//      return "Div zero!";
//    case Mod_zero:
//      return "Mod zero!";
//    default:
//      return "unknown error!";
//  }   
//}
//
//int Div(int x, int y)
//{
//  if(0 == y)
//  {
//    exit_code = Div_zero; 
//    return -1;
//  }
//  else
//  {
//    _exit(31);
//  }
//}
//
//int main()
//{
  //int *p = NULL;
  //while(1)
  //{
  //  printf("I am a process, pid: %d\n", getpid());
  //  sleep(1);
  //  exit(123);
  //  //*p = 100; //野指针 
  //}


  //int result = Div(10, -10);
  //printf("result: %d [%s]\n", result, CodeToErrString(exit_code));
  //_exit(31);
//  result = Div(10, 0);
//  printf("result: %d [%s]\n", result, CodeToErrString(exit_code));
//
//  return exit_code;

  //int errcode = 0;
  //for(errcode = 0; errcode <= 255; errcode++)
  //{
  //  printf("%d: %s\n", errcode, strerror(errcode));
  //}
  
  //binprintf("I am process, pid: %d, ppid: %d\n", getpid(), getppid());
//  sleep(2);
//
//  return 0;
//}
